package com.cindata

import com.cindata.dic.PrecinctTypeDict
import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

@Secured(['isAuthenticated()'])
@Transactional
class PrecinctController
{

    def springSecurityService
    def dataSource
    //static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index()
    {

    }

    def newIndex()
    {

    }

    def getInitData()
    {
        def result = ["success": true]
        def cityArr = City.executeQuery("select distinct e.city as city from Estate e ")
        result["cityArr"] = cityArr
        try
        {
            def user = User.findById(springSecurityService.principal.id)
            //登录用户
            def userAccount = user.account
            // 登录用户可以访问的Account
            def userManageAccount = user.getCurUserManageAccount()
            def accountHashArr = Account.ToHashMapArr(userManageAccount)
            // 整理成上下级关系
            def accountLeveArr = Account.GetTreeDataByArr(accountHashArr)
            //CustomRegion.PushCustomRegionIntoSourceTree(accountLeveArr,"com.cindata.Account")
            // 获得开发商列表
            def developerArr = Developer.ToHashMapArr(Developer.all)
            //CustomRegion.PushCustomRegionIntoSourceTree(developerArr,"com.cindata.Developer")
            //用户所属机构
            result["success"] = true
            result["accountArr"] = accountLeveArr
            result["developerArr"] = developerArr
            result["myAccount"] = userAccount
        }
        catch (Exception e)
        {
            result["success"] = false
            result["accountArr"] = []
            result["developerArr"] = []
            result["error"] = e.getMessage()
            e.printStackTrace()
        }

        render(result as JSON)
    }

    /*
    * 获得自定义区域数据
     */

    def getCustomRegionData()
    {

        def sourceId = params["sourceId"]
        def sourceClass = params["sourceClass"]
        def result = ["success": true]
        try
        {
            def customRegionArr = CustomRegion.findAllBySourceIdAndSourceClass(sourceId, sourceClass)
            result["success"] = true
            result["customRegionArr"] = customRegionArr
        }
        catch (Exception e)
        {
            result["success"] = false
            result["customRegionArr"] = []
            result["error"] = e.getMessage()
            e.printStackTrace()
        }

        render(result as JSON)
    }

    /*
    * 显示机构数据
     */

    def mapAccountData()
    {

        def result = ["success": true]
        def mapDataList = []
        def sqlParams = [:]
        def city = params["city"]
        //城市
        def accountName = params["keyword"]
        //网点机构名称
        try
        {
            def user = User.findById(springSecurityService.principal.id)
            //登录用户
            def userAccount = user.account
            // 登录用户可以访问的Account
            def userManageAccount = user.getCurUserManageAccount()
            //用户所属机构
            if (!userAccount)
            {
                result["mapDataList"] = mapDataList
                render([result: result] as JSON)
                return
            }
            //全国下的市网点
            def accountSql = " select new map( c.x as lng ,c.y as lat ,count(o.id) as count ) from Account o join o.city c where 1=1 "
            //网点机构名称
            if (city && city != '-1')
            {
                accountSql += " and o.city.zoneNumber = :city "
                sqlParams["city"] = city
            }
            if (accountName && accountName != '')
            {
                accountSql += " and o.name like :accountName "
                sqlParams["accountName"] = "%" + accountName + "%"
            }
            if (userManageAccount && userManageAccount.size() > 0)
            {
                accountSql += " and e.account in (:accountArr) "
                sqlParams["accountArr"] = userManageAccount
            }
            accountSql += " group by c.name ,c.zoneNumber ,c.x,c.y "
            mapDataList = Account.executeQuery(accountSql, sqlParams)
            result["success"] = true
            result["mapDataList"] = mapDataList
        }
        catch (Exception e)
        {
            result["success"] = false
            result["mapDataList"] = mapDataList
            e.printStackTrace()
        }

        render([result: result] as JSON)
    }

    /*
    * 显示开发商数据
     */

    def mapDeveloperData()
    {

        def result = ["success": true]
        def mapDataList = []
        def sqlParams = [:]
        def city = params["city"]
        //城市
        def accountName = params["keyword"]
        //网点机构名称
        try
        {
            //全国下的市网点
            def accountSql = " select new map( c.x as lng ,c.y as lat ,count(o.id) as count ) from Developer d join o.city c where 1=1 "
            //网点机构名称
            if (city && city != '-1')
            {
                accountSql += " and o.city.zoneNumber = :city "
                sqlParams["city"] = city
            }
            if (accountName && accountName != '')
            {
                accountSql += " and o.name like :accountName "
                sqlParams["accountName"] = "%" + accountName + "%"
            }
            accountSql += " group by c.name ,c.zoneNumber ,c.x,c.y "
            mapDataList = Account.executeQuery(accountSql, sqlParams)
            result["success"] = true
            result["mapDataList"] = mapDataList
        }
        catch (Exception e)
        {
            result["success"] = false
            result["mapDataList"] = mapDataList
            e.printStackTrace()
        }

        render([result: result] as JSON)
    }

    /*
    * 显示机构数据
     */

    def accountData()
    {

        def result = ["success": true]
        //网点机构名称
        try
        {
            def user = User.findById(springSecurityService.principal.id)
            //登录用户
            def userAccount = user.account
            // 登录用户可以访问的Account
            def userManageAccount = user.getCurUserManageAccount()
            // 整理成上下级关系
            def accountLeveArr = Account.GetTreeDataByArr(userManageAccount)
            //用户所属机构
            result["success"] = true
            result["accountArr"] = accountLeveArr
            result["myAccount"] = userAccount
        }
        catch (Exception e)
        {
            result["success"] = false
            result["accountArr"] = []
            result["error"] = e.getMessage()
            e.printStackTrace()
        }

        render([result: result] as JSON)
    }

    /*
    * 存储区域数据
    */

    @Transactional
    def saveData()
    {
        def result = ["success": true]
        def id = params["id"]
        def name = params["name"]
        // def sourceName = params["sourceName"]
        def sourceId = params["sourceId"]
        def path = params["path"]
        def type = params["type"]
        def sourceClass = params["class"]
        def x = params["x"]
        def y = params["y"]
        def zoom = params["zoom"]
        def idList = params["idList"]
        def customRegion = null
        if (!id)
        {
            customRegion = new CustomRegion()
        }
        else
        {
            customRegion = CustomRegion.find(id)
        }
        customRegion.name = name
        PrecinctTypeDict precinctType = type
        customRegion.precinctType = precinctType
        customRegion.createDate = new Date()
        //Clob clob = new javax.sql.rowset.serial.SerialClob(path.toString().toCharArray())
        //clob.setString(0,path)
        customRegion.coordinates = path
        customRegion.isDeleted = false
        customRegion.sourceId = sourceId as Integer
        customRegion.sourceClass = sourceClass
        customRegion.x = x as Double
        customRegion.y = y as Double
        customRegion.zoom = zoom as Double
        customRegion.idList = idList
        customRegion.save()
        if (!customRegion.save())
        {
            result["success"] = false
            result["error"] = customRegion.errors.allErrors.join("\n")
        }
        else
        {
            result["customRegion"] = customRegion
        }
        render(result as JSON)
    }

    /*
    * 删除区域数据
    */

    @Transactional
    def deleteData()
    {
        def result = ["success": true]
        def id = params["id"] as Long
        def customRegion = CustomRegion.findById(id)
        try
        {
            customRegion.delete(flush: true)
        }
        catch (Exception ex)
        {
            result["success"] = false
            result["error"] = ex.getMessage()
        }
        render(result as JSON)
    }

    def getAccountInfo()
    {
        def user = User.findById(springSecurityService.principal.id)
        def accountList = new ArrayList()
        def city = params['city'];
        def name = params['name'];
        def map = new HashMap();
        def result = new HashMap()
        def sql = ' from Account o where o.id in ' + Account.FilterAccountSql(user)
        def count = 0
        if (name)
        {
            sql += 'and o.name like :name '
            map.name = '%' + name + '%';
        }
        try
        {
            count = Account.executeQuery(sql, map).toList().size();
            accountList = Account.executeQuery(sql, map, [max: params.max ?: 10, offset: params.offset ?: 0]);
            result["count"] = count
            result["accountList"] = accountList
            result["status"] = "success"
        }
        catch (Exception e)
        {
            e.printStackTrace()
            result["status"] = "false"
            render(result as JSON)
        }

        render(result as JSON)
    }

    def getRqInfoForRegion()
    {
        def db = new groovy.sql.Sql(dataSource)
        def result = new ArrayList();
        def city = params['city'];
        def sql =
            "SELECT\n" + "e.id,\n" + "	e.community_id,\n" + "	e.community_name,\n" + "	e.x,\n" + "	e.y\n" + "FROM\n" + "	estate e\n" + "LEFT JOIN area A ON e.city_id = A .area_id\n" + "WHERE\n" + "	A .zone_number = '" + city + "'"
        result = db.rows(sql).asList()
        render([result: result] as JSON)
    }
}
